
<style lang="less" scoped></style>

<template>
  <GlobalPopuoUI
    :type='$store.state.globalPopupInfo.type' 
    :show='$store.state.globalPopupInfo.show'
    :close="close"
    :phone="phone"
    :code="code"
    :isDisabled="isDisabled"
    :codeState="codeState"
    :num="num"
    :title='$store.state.globalPopupInfo.title'
    :lectuerInfo="$store.state.globalPopupInfo.lectuerInfo"
    :courseInfo="$store.state.globalPopupInfo.courseInfo"
    :onGetCode="onGetCode"
    :onSubmit="onSubmit"
    @onPhoneChange="onPhoneChange"
    @onCodeChange="onCodeChange"
  />
</template>

<script>
  import GlobalPopuoUI from './GlobalPopuoUI.vue';
  export default {
    name: "GlobalPopup",
    components: {
      GlobalPopuoUI,
    },
    data() {
      return {
        phone: '', // 手机号
        code: '', // 验证码
        codeState: 0, // 0 待获取 1 倒计时
        num: 60,
      }
    },
    created() {
    },
    computed: {
      isDisabled() {
        return !(this.phone?.length === 11 && this.code?.length === 4);
      }
    },
    destroyed() {
      clearInterval(this.timeId);
      this.$store.commit('setGlobalPopupInfo', {
        ...this.$store.state.globalPopupInfo,
        show: false,
      })
    },
    methods: {
      close(_, mark) {
        console.log('触发关闭',mark);
        clearTimeout(this.timeId);
        if (this.$store.state.globalPopupInfo.show === false) return false;
				this.$store.commit('setGlobalPopupInfo', {
          ...this.$store.state.globalPopupInfo,
          show: false,
        })
        setTimeout(() => {
          this.phone = '';
          this.code = '';
          this.codeState = 0;
        }, 300);
				if (mark) {
					console.log('验证成功');
					// 继续跳转路由
          if (this.$store.state.globalPopupInfo.next) {
            this.$store.state.globalPopupInfo.next();
            this.$store.commit('setGlobalPopupInfo', {
              ...this.$store.state.globalPopupInfo,
              next: null,
            })
          } else {
            setTimeout(() => {
              location.reload();
            }, 500);
          }
				} else {
					console.log('取消验证', this.$store.state.globalPopupInfo.from.fullPath);
          // 当来源地址为空时，返回主页
          const path = this.$store.state.globalPopupInfo.from.fullPath;
          if (path === '/') {
            this.$router.replace(`/${this.$channel}/home`);
          } else if (path === `/${this.$channel}/home` && location.href.includes('liveBack')) {
            this.$router.replace(`/${this.$channel}/home`);
          } else if (path === `/${this.$channel}/niceCourse` && location.href.includes('liveBack')) {
            this.$router.replace(`/${this.$channel}/niceCourse`);
          }
				};
      },
      verifyPhone() {
        if (this.phone.length === 0) {
          fun.toastMessage('手机号码为空');
          return false;
        }
        if (this.phone.length < 11) {
          fun.toastMessage('请填写完整的手机号码');
          return false;
        }
        if (!/(13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{8}/.test(this.phone)) {
          fun.toastMessage('请填写正确的手机号码');
          return false;
        }
        return true;
      },
      onPhoneChange(e) {
        if (e.target.value.length > 11) {
          this.phone = e.target.value = e.target.value.slice(0, 11);
        } else {
          this.phone = e.target.value;
        }
      },
      onCodeChange(e) {
        if (e.target.value.length > 4) {
          this.code = e.target.value = e.target.value.slice(0, 4);
        } else {
          this.code = e.target.value;
        }
      },
      // 获取验证码
      onGetCode() {
        // 状态验证
        if (this.codeState === 1) return false;
        // 手机号验证
        if (!this.verifyPhone()) return false;
        // 倒计时
        const run = () => {
          this.codeState = 1;
          this.timeId = setTimeout(() => {
            this.num -= 1;
            if (this.num === 0) {
              this.codeState = 0;
              clearTimeout(this.timeId);
              this.timeId = null;
              this.num = 60;
            } else {
              run();
            }
          }, 1000);
        };
        // 获取验证码
        this.$http.post("/h5live/sms/sendSmsCode", {}, {
          params: {
            mobile: this.phone,
            type: 3,
            mid: 'default_course'
          }
        }).then(res => {
          if(res.data.code === "000000") {
            fun.toastMessage('短信发送成功');
            run();
          } else {
            return Promise.reject(res.data);
          }
        }).catch(err => {
          fun.toastMessage(err.msg);
          console.error(err);
        });
      },
      onSubmit() {
        // 手机号验证
        if (!this.verifyPhone()) return false;
        // 验证码验证
        this.$http.post("/h5live/sms/verifyCode", {}, {
          params: {
            mobile: this.phone,
            type: 3,
            mid: 'default_course',
            code: this.code,
          }
        }).then(async res => {
          if(res.data.code === "000000") {
            fun.toastMessage('手机验证成功');
            window.sessionStorage.setItem(`${this.$channel}CourseSms`,this.phone)
            // 关闭popup
            this.close(true, true);
            // 刷新用户信息
            // fun.refreshUserInfo().then(() => {
            //   console.log('刷新用户信息成功');
            //   // 关闭popup
            //   this.close(true, true);
            // }).catch(() => {
            //   console.log('刷新用户信息失败');
            // })
          } else {
            return Promise.reject(res.data);
          }
        }).catch(err => {
          fun.toastMessage(err.msg);
          console.error(err);
        });
      },
    }
  };
</script>
